import 'package:dio/dio.dart';

import 'network_request.dart';
import 'network_response.dart';

/// 插件基类
class NetworkInterceptor extends Interceptor {
  /// 优先级 数字越小在插件列表中越靠前
  int get priority => 1;

  @override
  void onRequest(
    RequestOptions options,
    RequestInterceptorHandler handler,
  ) {
    if (options.extra[MappingKey.target] is TargetType) {
      final target = options.extra[MappingKey.target] as TargetType;
      willSend(options, handler, target);
    }
  }

  @override
  void onResponse(
    Response response,
    ResponseInterceptorHandler handler,
  ) {
    if (response.requestOptions.extra[MappingKey.target] is TargetType) {
      final target =
          response.requestOptions.extra[MappingKey.target] as TargetType;
      didReceive(response, handler, target);
    }
  }

  @override
  void onError(
    DioException err,
    ErrorInterceptorHandler handler,
  ) {
    if (err.requestOptions.extra[MappingKey.target] is TargetType) {
      final target = err.requestOptions.extra[MappingKey.target] as TargetType;
      didError(err, handler, target);
    }
  }

  /// 请求前
  void willSend(
    RequestOptions options,
    RequestInterceptorHandler handler,
    TargetType target,
  ) {
    handler.next(options);
  }

  /// 收到数据
  void didReceive(
    Response response,
    ResponseInterceptorHandler handler,
    TargetType target,
  ) {
    handler.next(response);
  }

  /// 请求遇到错误
  void didError(
    DioException err,
    ErrorInterceptorHandler handler,
    TargetType target,
  ) {
    handler.next(err);
  }
}
